package com.pds.web.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.mapper.SysDictDataMapper;
import com.pds.system.service.IFileUploadService;
import com.pds.web.device.entity.PdsTestOrganizationDevice;
import com.pds.web.device.mapper.PdsTestOrganizationDeviceMapper;
import com.pds.web.device.service.PdsTestOrganizationDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 检测机构仪器设备表
 *
 * @author srf sunlightcs@gmail.com
 * @since 1.0.0 2024-02-19
 */
@Service("pdsTestOrganizationDeviceService")
public class PdsTestOrganizationDeviceServiceImpl extends ServiceImpl<PdsTestOrganizationDeviceMapper, PdsTestOrganizationDevice> implements PdsTestOrganizationDeviceService {
    @Resource
    private PdsTestOrganizationDeviceMapper pdsTestOrganizationDeviceMapper;
    @Autowired
    IFileUploadService fileUploadService;
    @Autowired
    SysDictDataMapper sysDictDataMapper;

    @Override
    public List<PdsTestOrganizationDevice> selectList(PdsTestOrganizationDevice pdsTestOrganizationDevice) {
        QueryWrapper<PdsTestOrganizationDevice> wrapper = new QueryWrapper<>();
        Long organizationId = pdsTestOrganizationDevice.getOrganizationId();
        String deviceName = pdsTestOrganizationDevice.getDeviceName();
        String status = pdsTestOrganizationDevice.getStatus();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //检测机构只能查询自己机构的仪器
        if(user.getDept().getType().intValue()==1){
            wrapper.eq("organization_id",user.getDept().getOrganizationId());
        }else {
            if (!Objects.isNull(organizationId)) {
                wrapper.eq("organization_id", organizationId);
            }
        }
        if(!Objects.isNull(deviceName) && !deviceName.isEmpty()){
            wrapper.like("device_name",deviceName);
        }
        if(!Objects.isNull(status) && !status.isEmpty()){
            wrapper.eq("status",status);
        }
        //按设备类型查询
        if(StringUtils.isNotEmpty(pdsTestOrganizationDevice.getDeviceType())){
            wrapper.eq("device_type",pdsTestOrganizationDevice.getDeviceType());
        }
        wrapper.orderByDesc("create_time").orderByAsc("id");
        List<PdsTestOrganizationDevice> pdsTestOrganizationDevices = pdsTestOrganizationDeviceMapper.selectList(wrapper);
        //仪器类型
        for (int i = 0; i < pdsTestOrganizationDevices.size(); i++) {
            PdsTestOrganizationDevice device = pdsTestOrganizationDevices.get(i);
            String dictLabel = sysDictDataMapper.selectDictLabel("device_type", device.getDeviceType());
            device.setDeviceTypeLabel(dictLabel);
        }
        return pdsTestOrganizationDevices;
    }

    @Override
    public PdsTestOrganizationDevice queryById(Long id) {
        return pdsTestOrganizationDeviceMapper.selectById(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public PdsTestOrganizationDevice insert(PdsTestOrganizationDevice pdsTestOrganizationDevice) {
        Date date = DateUtils.parseDate(DateUtils.getTime());
        checkNone(pdsTestOrganizationDevice,0);
        pdsTestOrganizationDevice.setStatus("1");
        pdsTestOrganizationDevice.setCreateTime(date);
        pdsTestOrganizationDeviceMapper.insert(pdsTestOrganizationDevice);
        return pdsTestOrganizationDevice;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Boolean update(PdsTestOrganizationDevice pdsTestOrganizationDevice) {
        Date date = DateUtils.parseDate(DateUtils.getTime());
        checkNone(pdsTestOrganizationDevice,0);
        pdsTestOrganizationDevice.setUpdateTime(date);
        return pdsTestOrganizationDeviceMapper.updateById(pdsTestOrganizationDevice) > 0;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        return pdsTestOrganizationDeviceMapper.deleteById(id) > 0;
    }

    /**
     * 导入检测仪器
     * @param dataList excel数据
     * @param map 图片信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importDevices(List<PdsTestOrganizationDevice> dataList, Map map) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        int row = 1;
        for (PdsTestOrganizationDevice device : dataList) {
            //第3列为设备图片，第9列校准证图片
            String devicePictureKey = row+"-3";
            String correctAttachmentKey = row+"-9";
            String devicePicture = map.get(devicePictureKey)==null ? null : String.valueOf(map.get(devicePictureKey));
            String correctAttachment = map.get(correctAttachmentKey)==null ? null : String.valueOf(map.get(correctAttachmentKey));
            if(StringUtils.isEmpty(devicePicture)){
                throw new Exception("第"+(row+1)+"行，请添加设备图片，如果是空行，请删除后重试");
            }
            if(StringUtils.isEmpty(correctAttachment)){
                throw new Exception("第"+(row+1)+"行，请添加校验证图片，如果是空行，请删除后重试");
            }
            checkNone(device,row+1);
            device.setDevicePicture(devicePicture);
            device.setCorrectAttachment(correctAttachment);
            device.setStatus("1");//默认状态是正常使用中
            device.setCreateBy(user.getNickName());
            device.setOrganizationId(user.getDept().getOrganizationId());
            device.setOrganizationName(user.getDept().getDeptName());
            row++;
        }
        pdsTestOrganizationDeviceMapper.batchInsert(dataList);
    }

    /**
     * 检查是否有必填项未输入
     * @param device  仪器信息
     * @param row 批量导入时，所在excel行号
     */
    private void checkNone(PdsTestOrganizationDevice device,int row) {
        String msg = "";
        if(row>1){
            msg = "第"+row+"行，";
        }
        Assert.hasLength(device.getDeviceName(),msg+"仪器名称不能为空！");
        Assert.hasLength(device.getDeviceCode(),msg+"仪器编码不能为空！");
        Assert.hasLength(device.getDeviceType(),msg+"仪器类型不能为空！");
        Assert.hasLength(device.getDeviceModel(),msg+"仪器型号不能为空！");
        Assert.hasLength(device.getDeviceBrand(),msg+"仪器品牌不能为空！");
        Assert.notNull(device.getCalibrationDate(),msg+"校准日期不能为空！");
        Assert.hasLength(device.getCalibrator(),msg+"校准员不能为空！");
        Assert.notNull(device.getRecalibrationDate(),msg+"建议再校准日期不能为空！");
    }


}
